// 浏览器环境检测工具

/**
 * 检测是否在微信浏览器中
 * @returns {boolean}
 */
export const isWeChat = () => {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes('micromessenger');
};

/**
 * 检测是否在QQ浏览器中
 * @returns {boolean}
 */
export const isQQ = () => {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes('qq/') || ua.includes('qqbrowser');
};

/**
 * 检测是否在支付宝内置浏览器中
 * @returns {boolean}
 */
export const isAlipay = () => {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes('aliapp') || ua.includes('alipay');
};

/**
 * 检测是否在移动设备上
 * @returns {boolean}
 */
export const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};

/**
 * 检测是否在iOS设备上
 * @returns {boolean}
 */
export const isIOS = () => {
  return /iPad|iPhone|iPod/.test(navigator.userAgent);
};

/**
 * 检测是否在Android设备上
 * @returns {boolean}
 */
export const isAndroid = () => {
  return /Android/.test(navigator.userAgent);
};

/**
 * 检测是否在Safari浏览器中
 * @returns {boolean}
 */
export const isSafari = () => {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes('safari') && !ua.includes('chrome') && !ua.includes('chromium');
};

/**
 * 检测是否支持文件下载
 * 在某些环境中，download属性可能不被支持
 * @returns {boolean}
 */
export const supportsDownload = () => {
  // 微信、QQ、支付宝等内置浏览器通常不支持download属性
  if (isWeChat() || isQQ() || isAlipay()) {
    return false;
  }
  
  // 检测是否支持download属性
  const a = document.createElement('a');
  return typeof a.download !== 'undefined';
};

/**
 * 检测是否支持现代剪贴板API
 * @returns {boolean}
 */
export const supportsClipboardAPI = () => {
  return !!(navigator.clipboard && window.isSecureContext);
};

/**
 * 检测是否支持Blob和URL.createObjectURL
 * @returns {boolean}
 */
export const supportsBlobURL = () => {
  try {
    return !!(window.Blob && window.URL && URL.createObjectURL);
  } catch (e) {
    return false;
  }
};

/**
 * 获取浏览器信息
 * @returns {object}
 */
export const getBrowserInfo = () => {
  const ua = navigator.userAgent;
  return {
    userAgent: ua,
    isWeChat: isWeChat(),
    isQQ: isQQ(),
    isAlipay: isAlipay(),
    isMobile: isMobile(),
    isIOS: isIOS(),
    isAndroid: isAndroid(),
    isSafari: isSafari(),
    supportsDownload: supportsDownload(),
    supportsClipboardAPI: supportsClipboardAPI(),
    supportsBlobURL: supportsBlobURL(),
  };
};

/**
 * 检测最佳的导出方式
 * @returns {string} 'download' | 'dialog' | 'copy'
 */
export const getBestExportMethod = () => {
  const info = getBrowserInfo();
  
  // 如果支持下载且不在受限环境中，优先使用下载
  if (info.supportsDownload && info.supportsBlobURL && !info.isWeChat && !info.isQQ && !info.isAlipay) {
    return 'download';
  }
  
  // 如果支持剪贴板API，使用复制
  if (info.supportsClipboardAPI) {
    return 'copy';
  }
  
  // 最后回退到对话框方式
  return 'dialog';
};

/**
 * 记录浏览器环境信息（用于调试）
 */
export const logBrowserInfo = () => {
  const info = getBrowserInfo();
  console.log('浏览器环境信息:', info);
  console.log('推荐导出方式:', getBestExportMethod());
};
